package com.ecloud.gardenscenter.mqtt;

import com.ecloud.gardenscenter.mqtt.constant.MqttMessageArrivedCall;
import lombok.Data;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;

/**
 * @author Squbi
 */
@Data
public class MqttTemplate {
    private final MqttClientFactory factory;
    private final String clientId;
    private MqttClient client;

    public MqttTemplate(MqttClientFactory factory, String clientId, MqttMessageArrivedCall call) throws MqttException {
        this.factory = factory;
        this.clientId = clientId;
        this.client = factory.getClient(clientId);
        MqttCallbackImpl callback = new MqttCallbackImpl(this, call);
        this.client.setCallback(callback);
    }

    public MqttTemplate(MqttClientFactory factory, String clientId, MqttCallback callback) throws MqttException {
        this.factory = factory;
        this.clientId = clientId;
        this.client = factory.getClient(clientId);
        this.client.setCallback(callback);
    }

    public void reConn() throws MqttException {
        this.factory.reConn(this.client);
    }

    public void publish(String topic, MqttMessage message) throws MqttException {
        this.client.publish(topic, message);
    }

    public void subscribe(String topic, int qos) throws MqttException {
        this.client.subscribe(topic, qos);
    }
}
